package com.algorithm.core;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.spec.SecretKeySpec;

/**
 * <h3>密钥管理器</h3><br>
 * 这个类用于生成密钥，并将密钥保存在文件中，以便后续使用。
 * 
 * @author 汪海伟
 *
 */
public class KeyManager {
    public static Key generateDETKey(String password, String columnName, String onionType)
            throws NoSuchAlgorithmException {
        byte[] colNameBytes = columnName.getBytes();
        byte[] keyBytes = "1234567812345678".getBytes();
        int row = (int) Math.ceil((double) colNameBytes.length / 16);
        byte[][] bytesArray = new byte[row][16];
        // 填充生成byte二维数组
        for (int i = 0, k = 0; i < row; i++) {
            for (int j = 0; j < 16; j++) {
                // 若colName长度不足，则从头开始填充
                if (k == colNameBytes.length) {
                    k = 0;
                }
                bytesArray[i][j] = colNameBytes[k++];
            }
        }
        // 异或计算
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < 16; j++) {
                keyBytes[j] = (byte) (keyBytes[j] ^ bytesArray[i][j]);
            }
        }
        SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
        return key;

    }
}
